<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>Heroku2</title>
    <script
      crossorigin
      src="https://unpkg.com/react@16/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
    ></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
    <script
      crossorigin
      src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"
    ></script>
    <script src="https://cdn.jsdelivr.net/npm/babel-regenerator-runtime@6.5.0/runtime.min.js"></script>
  </head>
  <body>
    <div class="main">
      <div class="section" id="app1"></div>
    </div>
    <script type="text/babel">
      let rtc;
      (async () => {
        const socket = io("https://serene-anchorage-28732.herokuapp.com/");

        const peer = (rtc = new RTCPeerConnection({
          iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
        }));
        peer.onicecandidate = ({ candidate }) => {
          if (!candidate) {
            console.log("emit");
            socket.emit("sdp", {
              sdp: JSON.stringify(peer.localDescription),
              roomId: "test",
            });
          }
        };

        const channel = peer.createDataChannel("chat");
        channel.onmessage = (ev) => {
          console.log(new TextDecoder("utf-8").decode(ev.data));
          channel.send("pong");
        };
        channel.onopen = () => {
          console.log("open");
        };
        channel.onclose = (e) => {
          console.log("close", e);
        };
        channel.onerror = (e) => {
          console.log("error", e);
        };

        await new Promise((r) => (peer.onnegotiationneeded = r));

        socket.emit("join", { roomId: "test" });
        console.log("join");
        socket.on("join", async () => {
          const offer = await peer.createOffer();
          await peer.setLocalDescription(offer);
          console.log("offer");
        });

        socket.on("sdp", async (data) => {
          console.log("on sdp", data);
          const answer = JSON.parse(data.sdp);
          await peer.setRemoteDescription(answer);
        });
      })();

      const App = () => {
        return <div>offer</div>;
      };

      ReactDOM.render(App(), document.getElementById("app1"));
    </script>
  </body>
</html>
